define(function(require,exports,module){
	//初始化相册上传
	exports.getToken=function(){
		var x=$.ajax({
			url:'/Photo/getToken.html',
			async:false,
			dataType:'json'
		});
		return x.responseJSON['uptoken'];
	}
	exports.changeImg=function(key,callback){
	    require('dialog');
	    var td2=key ? '<td class="ShowImg" style="border:1px solid #d1d1d1;padding:10px 0"><img src="http://static.sssui.com/ylh/'+key+'?imageView2/1/w/380/h/250/q/75&v=2" /></td>' : '';
	    var td1=key ? '<td>原图</td><td>新图</td>' : '<td>选择图片</td>';
	    var td3=key ? 'colspan="2"' : '';
		var ImgHtml=[''+
			'<div id="UploadDiv">'+
			'	<table>'+
			'		<tr>'+td1+'</tr>'+
			'		<tr>'+td2+
			'			<td class="ShowImg" style="border:1px solid #d1d1d1;padding:10px;"><a id="selectImg" href="javascript:;"><img src="" alt=""></a></td>'+
			'		</tr>'+
			'		<tr>'+
			'			<td '+td3+' height="60" valign="middle" align="right">'+
			'				<span id="UploadTips" class="fl"></span>'+
			'				<button type="button" class="btn btn-default" id="StartUpload"><i class="fa fa-upload"></i>上传</button>'+
			'			</td>'+
			'		</tr>'+
			'	</table>'+
			'</div>'].join('');
	    var UploadDiv=new dialog({
	    	title:'上传图片'
	    });
	    UploadDiv.showModal();
		require.async('/static/plugins/WebUploader/webuploader.min',function(){
			UploadDiv.content(ImgHtml);
		    var $wrap = $('#UploadDiv'),
		    // 上传按钮
		    $upload = $wrap.find('#StartUpload'),
		    tips=$('#UploadTips'),
		    // 添加的文件总大小
		    fileSize = 0,
		    // 优化retina, 在retina下这个值是2
		    ratio = window.devicePixelRatio || 1,
		    // 缩略图大小
		    thumbnailWidth = 380 * ratio,
		    thumbnailHeight = 250 * ratio,
		    // 可能有pedding, ready, uploading, confirm, done.
		    state = 'pedding',
		    // 所有文件的进度信息，key为file id
		    percentages = {},
		    // WebUploader实例
		    uploader;
		    if ( !WebUploader.Uploader.support() ) {
		        alert( 'Web Uploader 不支持您的浏览器！如果你使用的是IE浏览器，请尝试升级 flash 播放器');
		        throw new Error( 'WebUploader does not support the browser you are using.' );
		    }
		    console.info($upload);
		    // 实例化
		    uploader = WebUploader.create({
		        pick: {
		            id: '#selectImg',
		            label: '点击选择图片'
		        },
		        paste: document.body,
		        accept: {
		            title: 'Images',
		            extensions: 'gif,jpg,jpeg,bmp,png',
		            mimeTypes: 'image/*'
		        },
		        // swf文件路径
		        swf:  '/static/plugins/WebUploader/Uploader.swf',
		        disableGlobalDnd: true,
		        chunked: false,
		        server: 'http://upload.qiniu.com',
		        fileNumLimit: 1,
		        fileSizeLimit: 2 * 1024 * 1024,    // 300 M
		        fileSingleSizeLimit: 2 * 1024 * 1024    // 3 M
		    });
		    uploader.on('error',function(msg,a,file) {
		    	tips.html('错误:'+msg);
			});
		    uploader.onUploadProgress = function( file, percentage ) {
		        var $li = $('#'+file.id),
		            $percent = $li.find('.progress span');
		        $percent.css( 'width', percentage * 100 + '%' );
		        percentages[ file.id ][ 1 ] = percentage;
		        //updateTotalProgress();
		    };
		    uploader.onFileQueued = function( file ) {
		    	uploader.reset();
	            var showError = function( code ) {
	                switch( code ) {
	                    case 'exceed_size':
	                        text = '文件大小超出';
	                        break;
	                    case 'interrupt':
	                        text = '上传暂停';
	                        break;
	                    default:
	                        text = '上传失败，请重试';
	                        break;
	                }
	                tips.html(text);
	            };
		        if ( file.getStatus() === 'invalid' ) {
		            showError( file.statusText );
		        } else {
		            // @todo lazyload
		            uploader.makeThumb( file, function( error, src ) {
		                if (error) {
		                    tips.html( '不能预览' );
		                    return;
		                }
		                var img = $('<img src="'+src+'"><div style="position: absolute;top:0;left: 0;width:100%;font-size:88px;animation: fa-spin .8s infinite;display:none;"><i class="fa fa-globe"></i></div>');
		                $('#selectImg .webuploader-pick').html(img);
			            var loading=$('#selectImg .webuploader-pick div');
			            loading.css('lineHeight',$('#selectImg .webuploader-pick').height()+'px');
		    			$upload.show();
		            }, thumbnailWidth, thumbnailHeight );
		            file.rotation = 0;
		        }
		    };
		    uploader.on('uploadSuccess',function(file,res ) {
		    	console.info(file,res);
		    	$('#selectImg .webuploader-pick div').hide();
		    	$upload.hide();
		    	if(!key){
			    	$.post('/Mylove/save.html',{
						cid:-1,
						title:file.name,
						size:file.size,
						format:file.ext,
						thu_img:res.key,
						img:res.key
					},function(d){
						callback && callback(res.key,d);
					});
			    }else{
					callback && callback(res.key);
			    }
		    });
		    uploader.on('uploadBeforeSend', function(block, data){
				data.token=exports.getToken();
				if(key){
					data.key='ylh/'+key;
				}
			});
		    uploader.onError = function( code ) {
		        tips.html( 'Eroor: ' + code );
		    };
		    $upload.off('click').on('click',function(e) {
		    	$('#selectImg .webuploader-pick div').show();
		        uploader.upload();
		    });
		    $('#selectImg .webuploader-pick').css('lineHeight',$('#selectImg').height());
		    $upload.hide();
		});
	}
});